package com.ycz.zheng_springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycz.zheng_springboot.entity.Menu;
import com.ycz.zheng_springboot.mapper.MenuMapper;
import com.ycz.zheng_springboot.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 岳彩郑
 * @since 2022-05-04
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    /**
     * 菜单mapper
     *
     * @param name
     * @return
     */
    @Override
    public List<Menu> findMenu(String name) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(name)) {
            queryWrapper.like("name", name);
        }
        //查询所有数据
        List<Menu> list = list(queryWrapper);
        List<Menu> parentNode = list.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList());//过滤出一级菜单
        for (Menu menu : parentNode) {
            //遍历一级菜单
            //获取一级菜单下的二级菜单  也就是筛选所有数据中pid为一级菜单id的数据
            List<Menu> childrenNode = list.stream().filter(menu1 -> menu1.getPid() != null && menu1.getPid().equals(menu.getId())).collect(Collectors.toList());//过滤出一级菜单下的子菜单
            menu.setChildren(childrenNode);//将子菜单设置到一级菜单中
        }
        return parentNode;
    }
}
